<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';

const props = defineProps({
  disabled: {
    type: Boolean,
    default: false
  }
});
const emit = defineEmits(['open', 'close']);


const showTooltip = ref(false);// 控制提示显示的状态
const isActive = ref(false);
const volumeLevel = ref(0); // 0-100 的音量级别
let audioContext: AudioContext | null = null;
let analyser: AnalyserNode | null = null;
let microphone: MediaStreamAudioSourceNode | null = null;
let animationFrameId: number | null = null;

function toggle() {
  isActive.value = !isActive.value;
  if (isActive.value) {
    startMicrophone();
    emit('open');
  } else {
    stopMicrophone();
    emit('close');
  }
}

async function startMicrophone() {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    audioContext = new AudioContext();
    analyser = audioContext.createAnalyser();
    analyser.fftSize = 256;

    microphone = audioContext.createMediaStreamSource(stream);
    microphone.connect(analyser);

    startVolumeMeter();
  } catch (error) {
    console.error('麦克风访问失败:', error);
    isActive.value = false;
  }
}

function stopMicrophone() {
  if (animationFrameId) {
    cancelAnimationFrame(animationFrameId);
    animationFrameId = null;
  }

  if (microphone) {
    microphone.disconnect();
    microphone = null;
  }

  if (analyser) {
    analyser.disconnect();
    analyser = null;
  }

  if (audioContext) {
    audioContext.close();
    audioContext = null;
  }

  volumeLevel.value = 0;
}

function startVolumeMeter() {
  const dataArray = new Uint8Array(analyser!.frequencyBinCount);

  function updateVolume() {
    analyser!.getByteFrequencyData(dataArray);

    let sum = 0;
    for (let i = 0; i < dataArray.length; i++) {
      sum += dataArray[i];
    }

    // 计算平均音量 (0-255)
    const average = sum / dataArray.length;
    // 转换为百分比 (0-100)
    volumeLevel.value = Math.min(Math.max(average / 2.55, 0), 100);

    animationFrameId = requestAnimationFrame(updateVolume);
  }

  updateVolume();
}

onUnmounted(() => {
  stopMicrophone();
});
</script>

<template>
  <div class="micro-button-wrapper" @mouseenter="showTooltip = true" @mouseleave="showTooltip = false">
    <div class="micro-button" @click="toggle" :style="{
    'background': `radial-gradient(circle, rgba(255,255,255,0.23) ${100 - volumeLevel}%, rgba(0,255,0,0.5) ${100 - volumeLevel}%, rgba(0,200,0,0.7) 100%)`
  }">
      <svg-icon :name="isActive ? 'speak_on' : 'speak_off'" color='#fff'></svg-icon>
    </div>

    <!-- 悬浮提示 -->
    <div v-show="showTooltip" class="tooltip">
      麦克风
    </div>
  </div>

</template>

<style scoped lang="scss">
.micro-button-wrapper {
  position: relative;
  display: inline-flex;

  .tooltip {
    position: absolute;
    bottom: calc(100% + 8px);
    left: 50%;
    transform: translateX(-50%);
    background-color: rgba(0, 0, 0, 0.7);
    color: white;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    white-space: nowrap;
    opacity: 0;
    transition: opacity 0.2s ease;
    pointer-events: none;
    z-index: 10;

    /* 提示框底部的小箭头 */
    &::after {
      content: '';
      position: absolute;
      top: 100%;
      left: 50%;
      transform: translateX(-50%);
      border-width: 4px;
      border-style: solid;
      border-color: rgba(0, 0, 0, 0.7) transparent transparent transparent;
    }
  }

  &:hover .tooltip {
    opacity: 1;
  }
}

.micro-button {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 26px;
  cursor: pointer;
  transition: background 0.1s ease;
  position: relative;
  overflow: hidden;

  &:hover {
    background-color: rgba(255,255,255,0.18);
  }

  &::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: v-bind('volumeLevel + "%"');
    background: rgba(0, 200, 0, 0.5);
    transition: height 0.1s ease;
    z-index: 0;
  }

  .svg-icon {
    position: relative;
    z-index: 1;
  }
}
</style>
